<?php
/**
 * Created by PhpStorm.
 * User: 黄城
 * Date: 2017/5/10
 * Time: 17:24
 * Desc: 奖金流水列表
 */

namespace Manage\Controller;


use Think\Page;

class BonusController extends BaseController
{
    public $map = [];

    public $parameter = [];

    public $pageNo;

    public function index()
    {
        $this->findWhere();

        $model = M();
        $list = $model->table(C('DB_PREFIX').'b2c_bonus_log a')
            ->join("left JOIN ". C('DB_PREFIX') ."b2c_members b ON  a.`member_id` = b.`member_id`")
            ->join("left JOIN ". C('DB_PREFIX') ."webpos_local_store c ON  a.`local_id` = c.`local_id`")
            ->where($this->map)->page($this->pageNo.", 20")
            ->field(['b.nickname', 'a.change', 'a.time', 'a.param', 'a.type', 'a.change_num', 'a.id', 'c.local_name'])->select();

        $changes = self::changeMsg();
        $types = self::typeMsg();
        foreach ($list as &$value){
            $value['time'] = date('Y-m-d H:i:s', $value['time']);
            $value['url'] = U('Detail', ['id'=>$value['id']]);
            $value['changeMsg'] = $changes[$value["change"]];
            switch ($value['type']){
                case 0:
                    $value['typeMsg'] = sprintf('<span style=\'color: #00CC33\'>%s</span>', $types[0]);
                    $value['change_num'] = sprintf('<span style=\'color: #00CC33\'>+%s</span>',
                        number_format($value['change_num'], 2, '.', ''));
                    break;
                case 1:
                    $value['typeMsg'] = sprintf('<span style=\'color: #FF0000\'>%s</span>', $types[1]);
                    $value['change_num'] = sprintf('<span style=\'color: #FF0000\'>%s</span>',
                        number_format($value['change_num'], 2, '.', ''));
                    break;
                default:
                    $value['typeMsg'] = '';
                    break;

            }
        }

        $count = $model->table(C('DB_PREFIX').'b2c_bonus_log a')
            ->join("left JOIN ". C('DB_PREFIX') ."b2c_members b ON  a.`member_id` = b.`member_id`")
            ->join("left JOIN ". C('DB_PREFIX') ."webpos_local_store c ON  a.`local_id` = c.`local_id`")
            ->where($this->map)->field([ 'a.id'])->count();
        $PageObject = new Page($count, 20, $this->parameter);
        $show = $PageObject->show();

        //门店
        $localInfo = $model->table(C('DB_PREFIX').'webpos_local_store')
            ->where(['local_status' => '1', 'is_self' => 0, 'is_open_distribution' => '1'])
            ->field(['local_id', 'local_name'])->select();


        $this->assign('data', $list);
        $this->assign('page', $show);
        $this->assign('locals', $localInfo);
        $this->assign('changes', $changes);
        $this->assign('types', $types);
        $this->assign('parameters', $this->parameter);
        unset($this->parameter['p']);
        $this->assign('export', $this->parameter);
        $this->display('Bonus/index');
    }

    /**
     * 条件封装
     */
    private function findWhere()
    {
        $local_id = I('local_id', 0, 'intval');
        $beginDate = I('begin_time', htmlspecialchars());
        $endDate = I('end_time', htmlspecialchars());
        $type = I('type', '2');
        $this->pageNo = I('p', 1);
        $field = I('field', '');
        $search = I('search', htmlspecialchars());

        //门店ID查询
        if ($local_id != 0){
            $this->map['a.local_id'] = $local_id;
            $this->parameter['local_id'] = $local_id;
        }
        //事件筛选
        if (!empty($beginDate) and !empty($endDate) and strtotime($beginDate) < strtotime($endDate.' 23:59:59')){
            $beginTime = strtotime($beginDate);
            $endTime = strtotime($endDate.' 23:59:59');

            $this->map['a.time'] = ['between', "$beginTime, $endTime"];
            $this->parameter['beginDate'] = $beginTime;
            $this->parameter['endDate'] = $endTime;
        }
        //事件类型
        if ($type != 2){
            $this->map['a.type'] = $type;
        }
        $this->parameter['type'] = $type;

        //查询类型
        switch ($field){
            case 'id':
                $this->map['a.id'] = (int)$search;
                $this->parameter['id'] = $search;
                break;
            case 'nickname':
                $this->map['b.nickname'] = ['like', "%$search%"];
                $this->parameter['nickname'] = $search;
                break;
            default:
                break;
        }
    }

    private static function changeMsg()
    {
        return [
            1 => '下级关注公众号 获得奖金',
            2 => '下级首次生成海 报获得奖金',
            3 => '下级购买商品  获得奖金',
            4 => '下级退款 扣除奖金',
            5 => '自己订单使用 抵扣奖金',
            6 => '自己退款  返还奖金',
            7 => '订单完结',
            8 => '取消订单 返回使用奖金',
            9 => '被邀请关注获得奖金'
        ];
    }

    private static function typeMsg()
    {
        return [
            2 => '全部',
            0 => '收益',
            1 => '扣除'
        ];
    }

    /**
     * 导出
     */
    public function export()
    {
        $this->findWhere();
        $list = M('b2c_bonus_log a')
            ->join("left JOIN ". C('DB_PREFIX') ."b2c_members b ON  a.`member_id` = b.`member_id`")
            ->join("left JOIN ". C('DB_PREFIX') ."webpos_local_store c ON  a.`local_id` = c.`local_id`")
            ->where($this->map)
            ->field(['b.nickname', 'a.change', 'a.time', 'a.param', 'a.type', 'a.change_num', 'a.id', 'c.local_name'])->select();
        if (count($list) == 0){
            echo "<script>alert('没有可导出的数据');history.go(-1);</script>";
            return false;
        }
        $changes = self::changeMsg();
        $types = self::typeMsg();
        foreach ($list as &$value){
            $value['time'] = date('Y-m-d H:i:s', $value['time']);
            $value['changeMsg'] = $changes[$value["change"]];
            $value['typeMsg'] = $types[$value["type"]];
        }

        $expCellName = [
            ['0', '流水号', 'id'], ['1', '会员昵称', 'nickname'], ['2', '所属店铺', 'local_name'], ['3', '变动类型', 'typeMsg'], ['4', '变动金额', 'change_num'], ['5', '改变原因', 'changeMsg'], ['6', '时间', 'time']
        ];
        $xlsTitle = iconv('utf-8', 'utf-8', '奖金流水记录');//文件名称
        $fileName = date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($list);
        Vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new \PHPExcel();

        $this->array_key_simple($objPHPExcel,$list);

        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1',  $xlsTitle.'  导出时间:' . date('Y-m-d H:i:s'));
        if ($dataNum > 0) {
            for ($i = 0; $i < $cellNum; $i++) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
            }

            //逻辑区
            for ($i = 0; $i < $dataNum; $i++) {
                for ($j = 0; $j < $cellNum; $j++) {
                    $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $list[$i][$expCellName[$j][2]]);
                }
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 详细
     */
    public function detail()
    {
        $id = I('id', 0, 'intval');
        if ($id == 0){
            echo "<script>alert('参数错误');history.go(-1);</script>";
            return false;
        }
        $info = M('b2c_bonus_log')->where(['id' => $id])->field(['change', 'param', 'time', 'change_num', 's_member_id'])->find();
        if (empty($info)){
            echo "<script>alert('参数错误');history.go(-1);</script>";
            return false;
        }
        switch ($info['change']){
            case 1:
                $list = M('b2c_members')->where(['member_id' => $info['s_member_id']])->field(['nickname'])->find();
                $msg = $list['nickname'].' '.date('Y-m-d H:i:s', $info['time']).' 关注公众号';
                break;
            case 2:
                $list = M('b2c_members')->where(['member_id' => $info['s_member_id']])->field(['nickname'])->find();
                $msg = $list['nickname'].' 于 '.date('Y-m-d H:i:s', $info['time']).' 首次生成专属海报！';
                break;
            case 3:
                list($member_id, $orderId, $orderAmount) = explode(',', $info['param']);
                $list = M('b2c_members')->where(['member_id' => $member_id])->field(['nickname'])->find();
                $msg = sprintf('<p>订单号：%s</p><p>昵称：%s</p><p>时间：%s</p><p>购买金额：￥%s</p>',
                    $orderId, $list['nickname'],date('Y-m-d H:i:s', $info['time']), $orderAmount);
                break;
            case 4:
                list($member_id, $orderId, $orderAmount) = explode(',', $info['param']);
                $list = M('b2c_members')->where(['member_id' => $member_id])->field(['nickname'])->find();
                $msg = sprintf('<p>订单号：%s</p><p>昵称：%s</p><p>时间：%s</p><p>退款金额：￥%s</p>',
                    $orderId, $list['nickname'],date('Y-m-d H:i:s', $info['time']), $orderAmount);
                break;
            case 5:
                list($orderId, $orderAmount) = explode(',', $info['param']);
                $msg = sprintf('<p>订单号：%s</p><p>时间：%s</p><p>使用奖金抵扣：￥%s</p>',
                    $orderId, date('Y-m-d H:i:s', $info['time']), abs($orderAmount));
                break;
            case 6:
                list($s_member_id,$order_id, $refund_amount) = explode(',', $info['param']);
                $msg = sprintf('<p>订单号：%s</p><p>时间：%s</p><p>返还奖金：￥%s</p>',
                    $order_id, date('Y-m-d H:i:s', $info['time']), $refund_amount);
                break;
            case 7:
                list($s_member_id,$order_id) = explode(',', $info['param']);
                $list = M('b2c_members')->where(['member_id' => $s_member_id])->field(['nickname'])->find();
                $msg = sprintf('<p>订单号：%s</p><p>昵称：%s</p><p>时间：%s</p><p>返还奖金：￥%s</p>',
                    $order_id, $list['nickname'], date('Y-m-d H:i:s', $info['time']), $info['change_num']);
                break;
            case 8:
                list($order_id, $refund_amount) = explode(',', $info['param']);
                $msg = sprintf('<p>订单号：%s</p><p>时间：%s</p><p>返还奖金：￥%s</p>',
                    $order_id, date('Y-m-d H:i:s', $info['time']), $refund_amount);
                break;
            case 9:
//                $list = M('b2c_members')->where(['member_id' => $info['s_member_id']])->field(['nickname'])->find();
                $msg = sprintf('%s  被邀请 关注并绑定手机，获得 %s奖金。',
                    date('Y-m-d H:i:s', $info['time']), $info['change_num']);
                break;
            default:
                $msg = '';
                break;
        }
        if (empty($msg)){
            echo "<script>alert('参数错误');history.go(-1);</script>";
            return false;
        }
        $this->assign('msg', $msg);
        $this->display('Bonus/info');
    }

    public function array_key_simple($objPHPExcel, $lists){
        $order_id_array = array_column($lists, 'id');
        $names = array_count_values($order_id_array);
        $order_key = array_keys($names);
        $order_values = array_values($names);

        $sum = count($order_id_array);
        for ($i=0; $i<$sum; $i++) {

            if ($order_values[$i] > 1) {
                $a = array_search($order_key[$i],$order_id_array);
                $objPHPExcel->getActiveSheet()->mergeCells('H' . ($a + 3).':H'.($a + 2 + $order_values[$i]));
                $objPHPExcel->getActiveSheet()->mergeCells('B' . ($a + 3).':B'.($a + 2 + $order_values[$i]));
            }
        }
    }

}
